package com.ruoyi.user.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.user.domain.YmCartEntity;
import com.ruoyi.user.domain.YmOrderEntity;
import com.ruoyi.user.domain.YmProductEntity;
import com.ruoyi.user.enums.BizCodeEnum;
import com.ruoyi.user.enums.OrderStateEnum;
import com.ruoyi.user.enums.ReqHandleExceptionEnum;
import com.ruoyi.user.exception.BizException;
import com.ruoyi.user.interceptor.LoginInterceptor;
import com.ruoyi.user.mapper.YmCartMapper;
import com.ruoyi.user.mapper.YmProductMapper;
import com.ruoyi.user.model.LoginUser;
import com.ruoyi.user.pojo.ReqHandleVo;
import com.ruoyi.user.pojo.YmCartVo;
import com.ruoyi.user.pojo.YmOrderVo;
import com.ruoyi.user.service.IYmOrderService;
import com.ruoyi.user.utils.JsonData;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车 Controller
 * 
 * @author zq
 * @date 2022-11-08
 */
@RestController
@RequestMapping("/ymapp/order")
@Slf4j
public class YmOrderController extends BaseController
{
    @Autowired
    private IYmOrderService ymOrderService;
    @Autowired
    private YmCartMapper ymCartMapper;
    @Autowired
    private YmProductMapper ymProductMapper;


    /**
     * 依据uid和ostate（收获状态），到购物车表中查出订单关联的商品（订单商品来源于加购商品），即使支付完成后订单关联的商品在购物车列表中
     * 还是存在，但是加购数量置为0，生成新订单时也不会将之前历史的加购商品也计入其中
     * ostate：为空串：表示查询全部订单  为0：未收货  为1：已收货   为2：退订   为3：禁用
     */
    @GetMapping("/queryOrder")
    public ReqHandleVo<YmOrderVo> queryOrder(@RequestParam("ostate") String ostate){
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        Long uid = loginUser.getId();
        System.out.println("uid = " + uid + ",ostate = " + ostate);
        ReqHandleVo<YmOrderVo> reqHandleVo = new ReqHandleVo<>();

        // 先根据uid和ostate到订单表中查出所关联的所有订单（未支付：关联的加购商品数量 > 0、已支付：关联的加购商品数量置为0）
        List<YmOrderEntity> ymOrders = ymOrderService.selectYmOrdersByUidAndOstate(uid,ostate);
        if(CollectionUtils.isEmpty(ymOrders)){
            // 订单列表为空
            reqHandleVo = reqHandleVo.buildError(ReqHandleExceptionEnum.ORDER_IS_EMPTY.getDesc());
//            log.info("reqHandleVo = {}",reqHandleVo);
            return reqHandleVo;
        }

        // 根据每个订单的orderId到购物车表中查出所关联的商品
        List<YmOrderVo> ymOrderVos = ymOrders.stream().map(ymOrder -> {
            YmOrderVo ymOrderVo = new YmOrderVo();
            // TODO
            BeanUtils.copyProperties(ymOrder, ymOrderVo);
            Long orderId = ymOrder.getId();
            List<YmCartEntity> cartsByOrderId = ymCartMapper.selectYmCartsByOrderId(orderId);
            List<YmProductEntity> products = cartsByOrderId.stream().map(cart -> {
                Long pid = cart.getPid();
                return ymProductMapper.selectYmProductById(pid);
            }).collect(Collectors.toList());

            if (products == null || products.size()==0){
                throw new BizException(BizCodeEnum.ORDER_PRODUCT_NOT_FOUNF);
            }
            ymOrderVo.setProduct(products);
            return ymOrderVo;
        }).collect(Collectors.toList());

        // 请求响应
        reqHandleVo.setData(ymOrderVos);
        reqHandleVo = reqHandleVo.buildSuccess("请求成功");
//        log.info("reqHandleVo = {}",reqHandleVo);
        return reqHandleVo;

    }

    /**
     * 根据订单id进行退订处理
     */
    @PostMapping("/cancelOrder")
    public ReqHandleVo<YmOrderVo> cancelOrder(@RequestBody YmOrderEntity ymOrderEntity){
        ReqHandleVo<YmOrderVo> reqHandleVo = new ReqHandleVo<>();
        boolean cancelResult = ymOrderService.cancelOrder(ymOrderEntity.getId());
        if(!cancelResult){
            reqHandleVo = reqHandleVo.buildError(ReqHandleExceptionEnum.NET_LOAD_ERROR.getDesc());
            return reqHandleVo;
        }
        reqHandleVo = reqHandleVo.buildSuccess("退订成功");
        return reqHandleVo;
    }


    /**
     * 前台不传任何多余参数，仅需到Cart表中查出指定uid加购数量 > 0的商品，生成对应的订单即可
     * @param ymOrderEntity
     * @return
     */
    @PostMapping("/addOrder")
    public ReqHandleVo<YmCartVo> addOrder(@RequestBody YmOrderEntity ymOrderEntity){
        ReqHandleVo<YmCartVo> reqHandleVo = new ReqHandleVo<>();
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        Long uid = loginUser.getId();
        ymOrderEntity.setUid(uid);
        int opResult = ymOrderService.addOrder(ymOrderEntity);
        if(opResult < 1){
            reqHandleVo = reqHandleVo.buildError(ReqHandleExceptionEnum.NET_LOAD_ERROR.getDesc());
            return reqHandleVo;
        }

        reqHandleVo = reqHandleVo.buildSuccess("订单生成成功");
//        log.info("reqHandleVo = {}",reqHandleVo);
        return reqHandleVo;

    }

    /**
     * 查询列表
     */
//    @PreAuthorize("@ss.hasPermi('myapp:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(YmOrderEntity ymOrderEntity)
    {
        startPage();
        List<YmOrderEntity> list = ymOrderService.selectYmOrderList(ymOrderEntity);
        return getDataTable(list);
    }


    /**
     * 支付接口
     * @return
     */
    @ApiOperation("支付接口")
    @PostMapping("/pay")
    public JsonData payOrder(@RequestBody YmOrderEntity ymOrderEntity){
        if(ymOrderEntity == null){
            return JsonData.buildError(BizCodeEnum.ORDER_NOT_FOUND);
        }
        log.info("ymOrderEntity post:{}",ymOrderEntity);
        JsonData jsonData = ymOrderService.payOrder(ymOrderEntity);
        log.info("pay jsonData:{}",jsonData);
        return jsonData;
    }

    /**
     * 确认收货
     * @return
     */
    @ApiOperation("确认收货")
    @PostMapping("/receive")
    public JsonData receive(@RequestBody YmOrderEntity ymOrderEntity){
        if(ymOrderEntity == null){
            return JsonData.buildError(BizCodeEnum.ORDER_NOT_FOUND);
        }
        log.info("ymOrderEntity post:{}",ymOrderEntity);
        JsonData jsonData = ymOrderService.receive(ymOrderEntity);
        log.info("pay jsonData:{}",jsonData);
        return jsonData;
    }
}
